package com.jinandi.app.service;

import java.util.Map;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.core.context.SecurityContextHolder;

import com.jinandi.app.domain.User;

/**
 * <抽象父类Service 代码复用>
 * @author CGC
 * @version [记录版本号, 2013-4-17]
 */
public abstract class BaseService {
	
	/**
	 * <分页，排序设置, 只支持单一的排序设置>
	 * @param map
	 * @return
	 * @author CGC 
	 * 创建日期:2013-4-19 下午1:11:41
	 */
	protected PageRequest getPageRequest(Map<String, String> map){
		int size = 10;
		int number = 1;
		Direction direction = Direction.DESC;
		String properties = "id";
		if(map.containsKey("jtPageSize")){
			size = Integer.valueOf(map.get("jtPageSize"));
		}
		if(map.containsKey("jtStartIndex")){
			number = Integer.valueOf(map.get("jtStartIndex"));
		}
		if(map.containsKey("jtSorting")){
			String [] a= map.get("jtSorting").split(" ");
			properties = a[0];
			direction = Direction.valueOf(a[a.length-1]);
		}
		return  new PageRequest(number, size,direction ,properties);
	}

	/**
	 * <获取当前用户>
	 * @return
	 * @author CGC 
	 * 创建日期:2013-4-17 上午10:46:27
	 */
	public User getCurrentUser() {
		if (SecurityContextHolder.getContext().getAuthentication() != null) {
			if (SecurityContextHolder.getContext().getAuthentication()
					.getPrincipal().toString().equals("roleAnonymous")) {
				return null;
			}
			try {
				return (User) SecurityContextHolder.getContext()
						.getAuthentication().getPrincipal();
			} catch (Exception e) {
				return null;
			}
		}

		return null;
	}
}
